<?php defined('SYSPATH') or die('No direct script access.');

class Model_Pattern extends ORM
{  
    protected $_table_name = 'patterns';
    protected $_reload_on_wakeup = false;
    
    public function get_patterns(Model_Mailbox $mailbox, $count = false)
    {
        $query = $this->_get_patterns_query()
                    ->where('mailbox_id', '=', $mailbox->id);
                    
        if ($count) {
            $result = $query->count_all();
            return $result;
        } 
        
        $patterns = $query
                    ->order_by('id', 'ASC')
                    ->find_all()
                    ->as_array();
        return $patterns;        
    }
    
    protected function _get_patterns_query()
    {
        return ORM::factory('pattern');
    }
    
    public function add_pattern(Model_Mailbox $mailbox, $name, $reply)
    {
        /*$user_id = 0;
        $user = Model_Auth::instance()->get_user();
        if ($user) {
            $user_id = $user->id;   
        }     */
        
        $company = Model_Main::get_company();
        if ($company->id != $mailbox->company_id) {
            throw new HTTP_Exception_404('Такой компании нет');    
        }
        
        $name       = Security::xss_clean($name);
        $reply      = Security::xss_clean($reply); 
        
        $this->mailbox_id   = $mailbox->id;
        $this->name         = $name;
        $this->reply        = $reply;       
        $this->save();
        
        return $this;  
    }
    
    public function edit_pattern($name, $reply)
    {
        $mailbox = ORM::factory('mailbox', $this->mailbox_id);
        $company = Model_Main::get_company();
        if ($company->id != $mailbox->company_id) {
            throw new HTTP_Exception_404('Такой компании нет');    
        }
        
        $name       = Security::xss_clean($name);
        $reply      = Security::xss_clean($reply);
        
        $this->name    = $name;
        $this->reply   = $reply;       
        $this->save();
        
        return $this;   
    }
}
